package com.yanqu.road.server.logic.recharge;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.recharge.GoldTokenOrder;
import com.yanqu.road.logic.bussiness.recharge.GoldTokenBussiness;
import com.yanqu.road.logic.bussiness.recharge.RechargeBussiness;
import com.yanqu.road.entity.recharge.RechargeOrder;
import com.yanqu.road.entity.recharge.ResultCode;
import com.yanqu.road.entity.enums.eOrderStatus;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.entity.recharge.ThirdPartyRechargeOrder;
import com.yanqu.road.pb.recharge.RechargeProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.RechargeModule;
import com.yanqu.road.server.gameplayer.module.recharge.GoldTokenRechargeModule;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.MallMgr;
import com.yanqu.road.server.manger.config.MallRechargeConfigMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.task.GameCommandTask;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.List;

public class RechargeManager {

	private static Logger logger = LogManager.getLogger(RechargeManager.class.getName());

	/**
	 * 离线玩家是否购买过基金
	 */
	public static boolean offlineHasBuyFund(long userId, int fundMallId){
		//内购订单
		List<RechargeOrder> rechargeOrderList = RechargeBussiness.getAllRechargeOrderList(userId);
		RechargeOrder rechargeOrder = RechargeManager.getHasBeChargeRechargeOrder(fundMallId, rechargeOrderList);
		if(null != rechargeOrder){
			return true;
		}
		//第三方订单
		List<ThirdPartyRechargeOrder> thirdPartyRechargeOrderList = RechargeBussiness.getThirdPartyRechargeOrderList(userId);
		ThirdPartyRechargeOrder thirdPartyRechargeOrder = RechargeManager.getHasBeChargeThirdPartyOrder(fundMallId, thirdPartyRechargeOrderList);
		if(null != thirdPartyRechargeOrder){
			return true;
		}
		return false;
	}

	/**
	 * 通过商品编号获取已到账订单信息
	 */
	public static RechargeOrder getHasBeChargeRechargeOrder(int mallId, List<RechargeOrder> rechargeOrderList){
		if(null != rechargeOrderList){
			for(RechargeOrder rechargeOrder : rechargeOrderList){
				if(rechargeOrder.getMallId() == mallId && rechargeOrder.getOrderStatus() == eOrderStatus.HasBeenCharged){
					return rechargeOrder;
				}
			}
		}
		return null;
	}

	/**
	 * 通过商品编号获取已到账订单信息
	 */
	public static ThirdPartyRechargeOrder getHasBeChargeThirdPartyOrder(int mallId, List<ThirdPartyRechargeOrder> thirdPartyOrderList){
		if(null != thirdPartyOrderList){
			for(ThirdPartyRechargeOrder rechargeOrder : thirdPartyOrderList){
				if(rechargeOrder.getMallId() == mallId && rechargeOrder.getOrderStatus() == eOrderStatus.HasBeenCharged){
					return rechargeOrder;
				}
			}
		}
		return null;
	}

	/**
	 * 充值支付成功发往玩家消息队列
	 */
	public static int msgNotifyRechargeSuccess(String orderNo) {
		RechargeOrder rechargeOrder = RechargeBussiness.getRechargeOrder(orderNo);
		Integer checkResult = checkRechargeOrder(orderNo, rechargeOrder);
		if (null != checkResult){
			return checkResult;
		}

		long userId = rechargeOrder.getUserId();
		YanQuMessage message = parseRechargeSuccessMsg(orderNo, userId, 0);

		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		/*PushMgr.buildPay(player,rechargeOrder,null);*/
		GameCommandTask cmdWrapper = new GameCommandTask(null, message, player);
		if (player != null) {
			/* 已登录玩家，提交到玩家指令执行队列 */
			player.setState(PlayerState.ONLINE);
			player.getCommandQueue().add(cmdWrapper);
		}else{
			if(MallMgr.isSubscribeMall(rechargeOrder.getMallId()) && !StringUtils.isNullOrEmpty(rechargeOrder.getSubscription())){
				GamePlayer cachePlayer = GamePlayerMgr.getPlayer(userId);
				if(null != cachePlayer) {
					cachePlayer.getModule(RechargeModule.class).loginLogic();
				}
			}
			logger.info("订单充值玩家{}不在线{}", userId, orderNo);
			return ResultCode.Success;
		}

		return 0;
	}

	/**
	* 描述：获取充值成功msg
	* 作者：zrq
	* 时间：2023/7/10
	* 参数：
	 充值类型，0：内充；1：第三方；2：通宝充值
	* 返回值：
	**/
	private static YanQuMessage parseRechargeSuccessMsg(String orderNo, long userId, int rechargeType) {
		RechargeProto.RechargeSuccessMsg.Builder reqMsg = RechargeProto.RechargeSuccessMsg.newBuilder();
		reqMsg.setOrderNo(orderNo);
		reqMsg.setRechargeType(rechargeType);

		return YanQuMessageUtils.buildMessageByte(Protocol.S_RECHARGE_SUCCESS, userId, reqMsg.build().toByteArray());
	}

	/**
	 * 检测订单状态
	 */
	private static Integer checkRechargeOrder(String orderNo, RechargeOrder rechargeOrder) {
		if (null == rechargeOrder) {
			logger.error("订单号不存在{}", orderNo);
			// 订单不存在
			return ResultCode.ChargeOrderIsNull;
		}
		// 判断订单状态是否正确
		if (rechargeOrder.getOrderStatus() == eOrderStatus.HasBeenCharged) {
			logger.error("订单已经充值过了{}", orderNo);
			// 该订单已经充值
			return ResultCode.OrderStatusIsError;
		}
		if (rechargeOrder.getOrderStatus() == eOrderStatus.ReturnIngots) {
			logger.error("订单已经返还元宝过了{}", orderNo);
			// 该订单已经返还元宝
			return ResultCode.OrderStatusIsError;
		}
		return null;
	}

	/**
	 * 通知支付成功，游戏内到账处理
	 */
	public static int notifyPlayerRechargeSuccess(String orderNo) {
		RechargeOrder rechargeOrder = RechargeBussiness.getRechargeOrder(orderNo);
		Integer checkResult = checkRechargeOrder(orderNo, rechargeOrder);
		if (null != checkResult){
			return checkResult;
		}

		// 获取玩家
		GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(rechargeOrder.getUserId());
		if (null == gamePlayer) {
			if(MallMgr.isSubscribeMall(rechargeOrder.getMallId()) && !StringUtils.isNullOrEmpty(rechargeOrder.getSubscription())){//是订阅商品，拉起玩家到内存，处理订单
				GamePlayer cachePlayer = GamePlayerMgr.getPlayer(rechargeOrder.getUserId());
				if(null != cachePlayer) {
					cachePlayer.getModule(RechargeModule.class).loginLogic();
				}
				logger.warn("订单充值玩家不在线,主动加载到内存处理订单userId:{},orderNo:{}", rechargeOrder.getUserId(), orderNo);
				return ResultCode.Success;
			}else {
				logger.warn("订单充值玩家不在线{}", orderNo);
				return ResultCode.Success;
			}
		} else {// 更改订单状态
			int retCode = gamePlayer.getModule(RechargeModule.class).rechargeSuccess(rechargeOrder,true);
			if (retCode != 0) {
				return ResultCode.AddIngotsError;
			}
		}
		return ResultCode.Success;
	}

	/**
	 * 充值支付成功发往玩家消息队列
	 */
	public static int msgNotifyThirdPartyRechargeSuccess(String platformOrderNo) {
		ThirdPartyRechargeOrder rechargeOrder = RechargeBussiness.getThirdPartyRechargeOrder(platformOrderNo);
		Integer checkResult = checkThirdPartyOrder(platformOrderNo, rechargeOrder);
		if (null != checkResult) {
			return checkResult;
		}

		long userId = rechargeOrder.getUserId();
		YanQuMessage message = parseRechargeSuccessMsg(platformOrderNo, userId, 1);

		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		/*PushMgr.buildPay(player,null,rechargeOrder);*/
		GameCommandTask cmdWrapper = new GameCommandTask(null, message, player);
		if (player != null) {
			/* 已登录玩家，提交到玩家指令执行队列 */
			player.setState(PlayerState.ONLINE);
			player.getCommandQueue().add(cmdWrapper);
		}else{
			logger.info("第三方订单充值玩家{}不在线{}", userId, platformOrderNo);
			return ResultCode.Success;
		}
		return 0;
	}

	/**
	 * 检测第三方充值状态
	 */
	private static Integer checkThirdPartyOrder(String platformOrderNo, ThirdPartyRechargeOrder rechargeOrder) {
		if (null == rechargeOrder) {
			logger.error("第三方订单号不存在{}", platformOrderNo);
			// 订单不存在
			return ResultCode.ChargeOrderIsNull;
		}
		// 判断订单状态是否正确
		if (rechargeOrder.getOrderStatus() == eOrderStatus.HasBeenCharged) {
			logger.error("第三方订单已经充值过了{}", platformOrderNo);
			// 该订单已经充值
			return ResultCode.OrderStatusIsError;
		}
		return null;
	}

	/**
	 * 通知支付成功，游戏内到账处理
	 */
	public static int notifyPlayerThirdPartyRechargeSuccess(String platformOrderNo) {
		ThirdPartyRechargeOrder rechargeOrder = RechargeBussiness.getThirdPartyRechargeOrder(platformOrderNo);
		Integer checkResult = checkThirdPartyOrder(platformOrderNo, rechargeOrder);
		if (null != checkResult) {
			return checkResult;
		}
		// 获取玩家
		GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(rechargeOrder.getUserId());
		if (null == gamePlayer) {
			logger.warn("第三方订单充值玩家不在线{}", platformOrderNo);
			return ResultCode.Success;
		} else {// 更改订单状态
			int retCode = gamePlayer.getModule(RechargeModule.class).thirdPartyRechargeSuccess(rechargeOrder,true);
			if (retCode != 0) {
				return ResultCode.AddIngotsError;
			}
		}
		return ResultCode.Success;
	}

	/**
	 * 最近7日订单价格获取价格相近的商品
	 */
	public static MallInfo getMallInfoByPrice(GamePlayer player, long price, ActivityConditionInfo activityConditionInfo, List<Integer> mallGradeList){
		MallInfo mallInfo = null;

		int index = 0;
		if(price > 0){
			for(int gradeId : mallGradeList){
				mallInfo = NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), gradeId);
				if(null != mallInfo){
					long tempPrice = 0;
					try{
						tempPrice = MallRechargeConfigMgr.getPrice(mallInfo);
//					tempPrice = Long.parseLong(mallInfo.getPrice());
					}catch (Exception e){

					}
					if(tempPrice >= price){
						break;
					}
				}
			}
			if (mallInfo != null) {
				index = NormalActivityMgr.getIndexByMallId(activityConditionInfo.getActivityId(), activityConditionInfo.getConditionId(), mallInfo.getMallId());
				player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.RechargeBaseIndex, index + 1);
			}
		}else {
			index = (int)player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.RechargeBaseIndex);
			//直接按历史档位，需要纠正下当前触发的最高档
			index = Math.min(index, mallGradeList.size() - 1);
		}

		//vip 最低档位限制
		int vipLv = VipMgr.getVipLv(player.getUserInfo().getVipExp());
		boolean isSmallR = NormalActivityMgr.isSmallR(activityConditionInfo.getActivityId(), vipLv);
		if (!isSmallR && vipLv >= activityConditionInfo.getParamList().get(0).intValue()) {
			int vipLowerLimitMallGrade = activityConditionInfo.getParamList().get(1).intValue();
			MallInfo lowerMallInfo = NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), vipLowerLimitMallGrade);
			if (lowerMallInfo != null) {
				long tempPrice = 0;
				try{
					tempPrice = MallRechargeConfigMgr.getPrice(lowerMallInfo);
//					tempPrice = Long.parseLong(lowerMallInfo.getPrice());
				}catch (Exception e){

				}
				if (mallInfo == null || tempPrice >= MallRechargeConfigMgr.getPrice(mallInfo)) {
					index = NormalActivityMgr.getIndexByMallId(activityConditionInfo.getActivityId(), activityConditionInfo.getConditionId(), lowerMallInfo.getMallId());
				}
			}
		}
		int grade = activityConditionInfo.getParamList().get(2).intValue();
		if (grade > 0) {
			int pushGiftNum = Integer.parseInt(NormalActivityMgr.getActivityInfo(activityConditionInfo.getActivityId()).getParam5());
			pushGiftNum = pushGiftNum > 0 ? pushGiftNum : 1;
			int pushMinIndex;
			int pushMaxIndex = index;
			if (index - (pushGiftNum - 1) >= 0) {
				pushMinIndex = index - (pushGiftNum - 1);
			} else {
				pushMinIndex = 0;
				pushMaxIndex = pushGiftNum  - 1;
			}
			if (mallGradeList.indexOf(grade) >= pushMinIndex && mallGradeList.indexOf(grade) <= pushMaxIndex) {
				return NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), grade);
			}
		} else if (Integer.parseInt(NormalActivityMgr.getActivityInfo(activityConditionInfo.getActivityId()).getParam5()) == 0) {
			return NormalActivityMgr.getRMBActivityMallInfoByGrade(activityConditionInfo.getActivityId(), mallGradeList.get(index));
		}
		return null;
	}

	public static int msgNotifyGoldTokenRechargeSuccess(String orderNo) {
		GoldTokenOrder goldTokenOrder = GoldTokenBussiness.getGoldTokenOrder(orderNo);
		if (null == goldTokenOrder) {
			logger.error("通宝订单号不存在，orderNo:{}", orderNo);
			return ResultCode.ChargeOrderIsNull;
		}
		if (1 == goldTokenOrder.getOrderStatus()) {
			logger.error("通宝订单已经充值过了,orderNo:{},userId:{}", orderNo, goldTokenOrder.getUserId());
			return ResultCode.OrderStatusIsError;
		}
		long userId = goldTokenOrder.getUserId();
		YanQuMessage message = parseRechargeSuccessMsg(orderNo, userId, 2);

		GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
		GameCommandTask cmdWrapper = new GameCommandTask(null, message, player);
		if (null != player) {
			player.setState(PlayerState.ONLINE);
			player.getCommandQueue().add(cmdWrapper);
		}
		return 0;
	}

	public static int notifyGoldTokenRechargeSuccess(String orderNo) {
		GoldTokenOrder goldTokenOrder = GoldTokenBussiness.getGoldTokenOrder(orderNo);
		if (null == goldTokenOrder) {
			logger.error("通宝订单号不存在，orderNo:{}", orderNo);
			return ResultCode.ChargeOrderIsNull;
		}
		if (1 == goldTokenOrder.getOrderStatus()) {
			logger.error("通宝订单已经充值过了,orderNo:{},userId:{}", orderNo, goldTokenOrder.getUserId());
			return ResultCode.OrderStatusIsError;
		}

		// 获取玩家
		GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(goldTokenOrder.getUserId());
		if (null != gamePlayer) {
			int retCode = gamePlayer.getModule(GoldTokenRechargeModule.class).rechargeSuccess(goldTokenOrder,true);
			if (0 != retCode) {
				return ResultCode.AddIngotsError;
			}
		} else {// 更改订单状态
			logger.warn("通宝订单充值玩家不在线,orderNo:{},userId:{}", orderNo, goldTokenOrder.getUserId());
			return ResultCode.Success;
		}
		return ResultCode.Success;
	}
}
